#!/usr/bin/python
'''
Takes fasta file and randomly reverse compliments contigs.
'''
import gzip
import sys
import os
import random
import string

def read_file(filepath):
	# define data structure.
	data = {}
	
	# Check if zipped.
	zipped = False
	if filepath.count(".gz"):
		zipped = True
	
	# Open file.
	seq = ""
	seqheader = ""
	first = True
	
	if zipped == True:
		fin = gzip.open(filepath,"r")
	else:
		fin = open(filepath,"r")
	for line in fin:
		# Skip comments.	
		if line[0] == "#": continue

		# first time.
		if first == True and line[0] == ">":
			seq = ""
			seqheader = line.strip().replace(">","")
			first = False
			continue		

		# finished seq.
		if line[0] == ">":
			# save data.
			data[seqheader] = seq.strip()

			# Reset variables.
			seq = ""
			seqheader = line.strip().replace(">","")
			continue

		# get seq.
		seq += line.strip()
			
	# Handle last close and return.
	data[seqheader] = seq.strip()
	fin.close()
	return data
		
	
	

# Parameters.
infile_file = sys.argv[1]

# Read in file.
ctgs = read_file(infile_file)

# Loop over contigs.
for ctg in ctgs:
	# print.
	print ">" + ctg
	
	# choose if we print contig or RC.
	ctgs[ctg] = ctgs[ctg].upper()
	if random.randint(0,1) == 0:
		# print normal.
		print ctgs[ctg]
	else:
		# print reverse compliment.
		print ctgs[ctg].translate(string.maketrans("ATCGN", "TAGCN"))[::-1]
		
